package cn.texous.easytalk.websocket.config;

import cn.texous.easytalk.commonutil.constant.RedisKey;
import cn.texous.easytalk.websocket.listener.EventMsgListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis config
 *
 * @author texousliu
 * @since 2019-08-28 13:41:12
 */
@Configuration
public class RedisConfig {

    @Autowired
    private EventMsgListener eventMsgListener;

    /**
     * 让监听器监听关心的话题
     * @param redisConnectionFactory redis connection factory
     * @return
     */
    @Bean
    public RedisMessageListenerContainer setRedisMessageListenerContainer(
            RedisConnectionFactory redisConnectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        //话题1
        container.addMessageListener(eventMsgListener,
                new ChannelTopic(RedisKey.CHANNEL_MANAGER_SYSTEM_EVENT_MSG));
        return container;
    }

    /**
     * redis template 配置
     * @param factory redis connection factory
     * @return
     */
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(factory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
        template.setKeySerializer(stringRedisSerializer);
        template.setValueSerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setHashValueSerializer(stringRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}
